import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import seaborn as sns

sns.set_theme()
# 设置中文字体路径（Windows系统）
ch_font = FontProperties(fname="C:/Windows/Fonts/simhei.ttf")

# 读取数据
df = pd.read_csv("加权后的分组得分.csv")
df = df[pd.to_numeric(df["year"], errors="coerce").notna()]
df["year"] = df["year"].astype(int)

# 构建压缩后的年份映射
sparse_years = [1920, 1935, 1941, 1944]

mapped_years = {}
pos = 0
for year in sorted(set(sparse_years)):
    mapped_years[year] = pos
    pos += 1  # 稀疏年份步长小

for year in range(1955, df["year"].max() + 1):
    mapped_years[year] = pos
    pos += 3  # 密集年份步长大

df = df[df["year"].isin(mapped_years)]
df["mapped_year"] = df["year"].map(mapped_years)

# 所有电影类型列
type_columns = [
    "joy_and_escapism",
    "Stimulation_and_Adventure",
    "Realism_and_Depth",
    "Anxiety_Conflict",
    "Documentary_and_Public",
    "Other",
]

# x轴刻度设置
xtick_positions = []
xtick_labels = []
for year in sorted(mapped_years):
    mapped = mapped_years[year]
    if year <= 1944 or year % 5 == 0:
        xtick_positions.append(mapped)
        xtick_labels.append(str(year))

# 每 3 个子图一页
group_size = 3
for i in range(0, len(type_columns), group_size):
    sub_types = type_columns[i : i + group_size]
    fig, axes = plt.subplots(
        nrows=len(sub_types), ncols=1, figsize=(14, 4 * len(sub_types)), sharex=True
    )

    if len(sub_types) == 1:
        axes = [axes]

    for j, col in enumerate(sub_types):
        ax = axes[j]

        # 年份聚合
        yearly = df.groupby(["year", "mapped_year"])[col].sum().reset_index()
        """
        min_val, max_val = yearly[col].min(), yearly[col].max()
        if max_val != min_val:
            yearly['normalized'] = (yearly[col] - min_val) / (max_val - min_val)
        else:
            yearly['normalized'] = 0  # 若全部相同
        """
        # 绘图
        ax.plot(yearly["mapped_year"], yearly[col], label=col, linewidth=2)
        ax.set_ylabel("归一化得分", fontproperties=ch_font)
        ax.set_title(f"{col} 的趋势变化", fontproperties=ch_font)
        ax.grid(True)
        ax.legend(loc="upper left", prop=ch_font)

    # 设置公共横轴
    axes[-1].set_xticks(xtick_positions)
    axes[-1].set_xticklabels(xtick_labels, rotation=45, fontproperties=ch_font)
    axes[-1].set_xlabel("年份（1920-1944 压缩）", fontproperties=ch_font)

    # 布局美化
    fig.suptitle(
        f"类型趋势图（第 {i // group_size + 1} 页）",
        fontsize=16,
        fontproperties=ch_font,
    )
    plt.tight_layout(rect=[0, 0, 1, 0.95])
    plt.show()
